/**
 * @description 中国地图
 */

import echarts from "../echart"
import { useEffect, useRef } from 'react';
import { getChartAPI } from "@/api/list";

function ChinaMap({ configData, themeConfig, limitNum }) {

  let { title, xColumn, api, echartsTheme, graphType } = configData
  const chartRef = useRef()

  useEffect(() => {

    // 如果themeConfig不是非空对象，这里echartsTheme会被 themeConfig覆盖
    let myChart = echarts.init(chartRef.current, echartsTheme)

    // 容器变化时，重渲染图表
    let resizeFn = () => {
      myChart && myChart.resize()
    }
    window.addEventListener('resize', resizeFn)


    getChartAPI(api).then(res => {
      if (!myChart) {
        return
      }

      let chartData = res.data

      const options = {
        backgroundColor: 'transparent',
        title: {
          text: title,
          left: "center",
        },
        visualMap: {
          min: 0,
          max: 100,
          text: ['High', 'Low'],
          calculable: true,
          seriesIndex: [0], //这个对应的是series的数组下标
          inRange: {
            color: ["#00467F", "#A5CC82"]
          }
        },
        // 提示框组件
        tooltip: {
          trigger: "item",
          formatter: "{b}<br/>{c} "
        },
        series: [
          {
            type: "map",
            map: 'china',
            geoIndex: 0,
            aspectScale: 0.75, //长宽比
            showLegendSymbol: false, // 存在legend时显示
            label: {
              show: true,
            },
            emphasis: {
              label: {
                show: false,
                color: "#fff"
              }
            },
            roam: true,
            animation: false,
            data: chartData.filter((item, index) => index < limitNum).map(item => ({ value: item.total, name: item[xColumn] }))
          }
        ]
      }


      // 绘制图表
      myChart.setOption(options);

    })

    // 组件卸载
    return () => {
      window.removeEventListener('resize', resizeFn)

      // myChart.dispose() 销毁实例。实例销毁后无法再被使用
      myChart.dispose()
      myChart = null
    }
  }, [])
  return (
    <div className='chart-box' ref={chartRef} ></div>
  )
}
export default ChinaMap